#!/usr/bin/env python
# coding:utf-8

import os,sys,time,datetime,common.db,common.roleinfo
from logging import *
from common.date_time import *

roleinfo=common.roleinfo.RoleInfo()

def trace_roleinfo(roleList):
    print 'start to statistic role info ...'
    counter = 0
    percent = 0
    for role in roleList:
        info=roleinfo.get(role[0],role[1],'accountid,rolename,gender,experience,logincount,FROM_UNIXTIME(lastlogouttime)')
        role[2] = info[2]
        role[3] = info[3]
        role[4] = info[4]
        role[5] = info[5]
        counter += 1
        if percent + 10 <= counter * 100 / len(roleList):
            percent = counter * 100 / len(roleList)
            print 'stat role info progress: %d%% %d/%d'%(percent,counter,len(roleList))

def trace_newplayers(curBill,roleList,startDate,endDate):
    print 'start to statistics new players (startDate=%s enddate=%s) ...'%(startDate,endDate)
    listDay = intervalDay(startDate,endDate)
    for day in listDay:
        strDay = day.replace('-','')
        strSql = 'select zoneid,roleid,logintime from dmz_bill_%s.login where logincount = 1'%(strDay)
        curBill.execute(strSql)
        rs = curBill.fetchone()
        while rs is not None:
            # zoneid,roleid,gender,experience,logincount,lastlogouttime,onlinetime,logindays,lastlogindate,pay,lastpaydate,gamecount
            roleList.append([rs[0],rs[1],0,0,0,'2009-09-20 10:00:00',0,0,strDay,0,'0',0])
            rs = curBill.fetchone()

def trace_online(curBill,roleList,startDate,endDate):
    print 'start to statistic online info (startDate=%s enddate=%s) ...'%(startDate,endDate)
    listDay = intervalDay(startDate,endDate)
    for day in listDay:
        print '    get online info of %s'%(day)
        strDay = day.replace('-','')
        for role in roleList:
            strSql = 'select sum(onlinetime) from dmz_bill_%s.logout where zoneid=%d and roleid=%d'%(strDay,role[0],role[1])
            curBill.execute(strSql)
            rs = curBill.fetchone()
            if rs is not None:
                if rs[0] is not None:
                    role[6] += rs[0]

def trace_login(curBill,roleList,startDate,endDate):
    print 'start to statistic login info (startDate=%s enddate=%s) ...'%(startDate,endDate)
    listDay = intervalDay(startDate,endDate)
    for day in listDay:
        print '    get login info of %s'%(day)
        strDay = day.replace('-','')
        for role in roleList:
            strSql = 'select count(*) from dmz_bill_%s.login where zoneid=%d and roleid=%d'%(strDay,role[0],role[1])
            curBill.execute(strSql)
            rs = curBill.fetchone()
            if rs is not None:
                if rs[0] is not None:
                    if rs[0] != 0:
                        role[7] += 1
                        role[8] = strDay

def trace_pay(curBill,roleList,startDate,endDate):
    print 'start to statistic pay info (startDate=%s enddate=%s) ...'%(startDate,endDate)
    listDay = intervalDay(startDate,endDate)
    for day in listDay:
        print '    get pay info of %s'%(day)
        strDay = day.replace('-','')
        for role in roleList:
            strSql = 'select sum(moneynew-moneyold) from dmz_bill_%s.money where zoneid=%d and roleid=%d and moneynew>moneyold and transid like \'%%TP28%%\''%(strDay,role[0],role[1])
            curBill.execute(strSql)
            rs = curBill.fetchone()
            if rs is not None:
                if rs[0] is not None:
                    if rs[0] != 0:
                        role[9] += rs[0]
                        role[10] = strDay

def trace_game(curBill,roleList,startDate,endDate):
    print 'start to statistic game info (startDate=%s enddate=%s) ...'%(startDate,endDate)
    listDay = intervalDay(startDate,endDate)
    for day in listDay:
        print '    get game count of %s'%(day)
        strDay = day.replace('-','')
        for role in roleList:
            strSql = 'select count(*) from dmz_bill_%s.balance_request where zoneid=%d and roleid=%d'%(strDay,role[0],role[1])
            curBill.execute(strSql)
            rs = curBill.fetchone()
            if rs is not None:
                if rs[0] is not None:
                    if rs[0] != 0:
                        role[11] += rs[0]

def trace_insert(curBill,roleList,createDate,traceDate):
    print 'start to insert trace info into db ...'
    for role in roleList:
        strSql = 'insert into statisticdb.DMZNewPlayerTraceDay (`TraceDate`,`ZoneID`,`CreateDate`,`RoleID`,`Gender`,`Experience`,`LoginCount`,`LastLogoutTime`,`OnlineTime`,`LoginDays`,`LastLoginDate`,`Pay`,`LastPayDate`,`GameCount`) values (%s,%d,%s,%d,%d,%d,%d,\'%s\',%d,%d,%s,%d,%s,%d)'%(traceDate.replace('-',''),role[0],createDate.replace('-',''),role[1],role[2],role[3],role[4],role[5],role[6],role[7],role[8],role[9],role[10],role[11])
        #print strSql
        try:
            curBill.execute(strSql)
        except Exception,data:
            print 'trace info insert error ...'

def NewPlayerTraceDay(strCurDay):

    cnnBill = common.db.connect('billDB')
    curBill = cnnBill.cursor()

    sevenDayAgo = GetDay(-7,strCurDay)
    forteenDayAgo = GetDay(-14,strCurDay)
    thirtyDayAgo = GetDay(-30,strCurDay)

    # delete current day trace info
    strDay = strCurDay.replace('-','')
    strSql = 'delete from statisticdb.DMZNewPlayerTraceDay where TraceDate=%s'%(strDay)
    nRowsCount = curBill.execute(strSql)
    cnnBill.commit()
    print 'delete new player trace info successful (deletedCount=%d)'%(nRowsCount)

    # current-day new players
    roleList1 = []
    trace_newplayers(curBill,roleList1,strCurDay,strCurDay)
    trace_roleinfo(roleList1)
    trace_online(curBill,roleList1,strCurDay,strCurDay)
    trace_login(curBill,roleList1,strCurDay,strCurDay)
    trace_pay(curBill,roleList1,strCurDay,strCurDay)
    trace_game(curBill,roleList1,strCurDay,strCurDay)
    trace_insert(curBill,roleList1,strCurDay,strCurDay)
    cnnBill.commit()
    
    # seven-day-ago new players
    roleList2 = []
    trace_newplayers(curBill,roleList2,sevenDayAgo,sevenDayAgo)
    trace_roleinfo(roleList2)
    trace_online(curBill,roleList2,sevenDayAgo,strCurDay)
    trace_login(curBill,roleList2,sevenDayAgo,strCurDay)
    trace_pay(curBill,roleList2,sevenDayAgo,strCurDay)
    trace_game(curBill,roleList2,sevenDayAgo,strCurDay)
    trace_insert(curBill,roleList2,sevenDayAgo,strCurDay)
    cnnBill.commit()

    # forteen-day-ago new players
    roleList3 = []
    trace_newplayers(curBill,roleList3,forteenDayAgo,forteenDayAgo)
    trace_roleinfo(roleList3)
    trace_online(curBill,roleList3,forteenDayAgo,strCurDay)
    trace_login(curBill,roleList3,forteenDayAgo,strCurDay)
    trace_pay(curBill,roleList3,forteenDayAgo,strCurDay)
    trace_game(curBill,roleList3,forteenDayAgo,strCurDay)
    trace_insert(curBill,roleList3,forteenDayAgo,strCurDay)
    cnnBill.commit()

    # thirty-day-ago new players
    roleList4 = []
    trace_newplayers(curBill,roleList4,thirtyDayAgo,thirtyDayAgo)
    trace_roleinfo(roleList4)
    trace_online(curBill,roleList4,thirtyDayAgo,strCurDay)
    trace_login(curBill,roleList4,thirtyDayAgo,strCurDay)
    trace_pay(curBill,roleList4,thirtyDayAgo,strCurDay)
    trace_game(curBill,roleList4,thirtyDayAgo,strCurDay)
    trace_insert(curBill,roleList4,thirtyDayAgo,strCurDay)
    cnnBill.commit()

    print 'trace new player success ...\n'

    curBill.close()
    cnnBill.close()


if __name__ != "__main__":
    
    if len(sys.argv) > 3:
        strBeginDay = sys.argv[2]
        strEndDay = sys.argv[3]
        if len(strBeginDay) != 10:
            log(ERROR,'Param is error!')
            sys.exit(0)
        if len(strEndDay) != 10:
            log(ERROR,'Param is error!')
            sys.exit(0)
        for strCurDay in intervalDay(strBeginDay,strEndDay):
            NewPlayerTraceDay(strCurDay)
    elif len(sys.argv) > 2:
        strCurDay = sys.argv[2]
        if len(strCurDay) != 10:
            log(ERROR,'Param is error!')
            sys.exit(0)
        NewPlayerTraceDay(strCurDay)
    else:
        strCurDay = GetDay(-1) ##"2010-01-14"
        NewPlayerTraceDay(strCurDay)



